package com.zkyc.framework.website.strategy.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zkyc.framework.common.constant.NumberConstant;
import com.zkyc.framework.common.exception.ResultCode;
import com.zkyc.framework.common.pojo.Organization;
import com.zkyc.framework.common.pojo.Pi;
import com.zkyc.framework.common.pojo.User;
import com.zkyc.framework.common.pojo.WebContent;
import com.zkyc.framework.common.utils.WebsiteUtil;
import com.zkyc.framework.common.vo.ResultVO;
import com.zkyc.framework.common.vo.website.ColumnDataPageVo;
import com.zkyc.framework.common.vo.website.ReplaceContentVo;
import com.zkyc.framework.common.vo.website.WebContentVo;
import com.zkyc.framework.website.client.RoleClient;
import com.zkyc.framework.website.client.UserClient;
import com.zkyc.framework.website.config.MathcingConfig;
import com.zkyc.framework.common.mapper.CenterMapper;
import com.zkyc.framework.website.mapper.ClickRateMapper;
import com.zkyc.framework.website.mapper.ContentMapper;
import com.zkyc.framework.common.mapper.OrganizationMapper;
import com.zkyc.framework.website.service.ApproveService;
import com.zkyc.framework.website.service.impl.ApproveServiceImpl;
import com.zkyc.framework.website.strategy.StrategyEnum;
import com.zkyc.framework.website.strategy.StrategyService;
import com.zkyc.framework.website.util.TokenUserUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * 官网
 */
@Service
public class AquaContentStrategyImpl implements StrategyService {

    @Autowired
    private ContentMapper contentMapper;
    @Autowired
    private ClickRateMapper clickRateMapper;
    @Autowired
    private RoleClient roleClient;
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private CenterMapper centerMapper;
    @Autowired
    private UserClient userClient;
    @Autowired
    private ApproveServiceImpl approveService;

    @Override
    public Integer fetchKey() {
        return StrategyEnum.Aqua.getKey();
    }

    @Override
    public ResultVO queryList() {
        List<Organization> organizations;
        String userId = TokenUserUtil.getCurrentUserId();
        String websiteId = WebsiteUtil.getWebsiteId();
        String dataRight = StringPool.ONE;
/*        if (StringUtils.isNotBlank(userId)) {
            dataRight = roleClient.getDataRight(websiteId, userId);
        }
        if (StringPool.ONE.equals(dataRight))*/
        userId = null;
        organizations = organizationMapper.findAllOrganization(userId);
        organizations.forEach(organization -> {
            if (organization.getOperateUserId() != null) {
                User user = getUser(organization.getOperateUserId());
                if (user != null) {
                    organization.setOperateUserName(user.getUsername());
                }
            }
            if (StringUtils.isNotBlank(organization.getOrganizationName())) {
                organization.setCenterName(organization.getOrganizationName());
                organization.setTreeType(NumberConstant.NUMBER_1);
            }
            if (organization.getChildren() != null) {
                organization.getChildren().forEach(center -> {
                    if ((center.getPi() != null && WebsiteUtil.hasAccessToken()) || StringPool.ONE.equals(websiteId)) {
                        try {
                            List<Pi> piList = new ArrayList<>();
                            String[] pis = center.getPi().split(",");
                            for (String userCode : pis) {
                                Pi pi = centerMapper.findCenterByUserCode(userCode, websiteId);
                                if (pi != null) {
                                    pi.setRejectReason(approveService.setRejectReason(pi.getId(),2));
                                    if (StringUtils.isNotBlank(pi.getPiInformation())) {
                                        JSONArray jsonArray = JSONArray.parseArray(pi.getPiInformation());
                                        pi.setPiInformationJSONArray(jsonArray);
                                    } else {
                                        pi.setPiInformationJSONArray(new JSONArray());
                                    }
                                    piList.add(pi);
                                }
                                center.setPiList(piList);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (center.getAttachementUrl() != null) {
                        JSONArray jsonArray = JSONArray.parseArray(center.getAttachementUrl());
                        center.setAttachementUrlJson(jsonArray);
                    } else {
                        center.setAttachementUrlJson(new JSONArray());
                    }
                    if (StringUtils.isNotBlank(center.getOperateUserId())) {
                        User user = getUser(center.getOperateUserId());
                        center.setOperateUserName(user.getUsername());
                    }
                    if (center.getPi() != null && WebsiteUtil.hasAccessToken() || StringPool.ONE.equals(websiteId)) {
                        String[] split = center.getPi().split(",");
                        ArrayList<String> pis = new ArrayList<>(Arrays.asList(split));
                        center.setPis(pis);
                    } else {
                        center.setPi(null);
                    }
                    center.setTreeType(NumberConstant.NUMBER_2);
                });
            }
        });

        return ResultVO.data(organizations);
    }

    private User getUser(String userId) {
        ResultVO<?> userById = userClient.getUserById(userId);
        JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(userById));
        return JSONObject.parseObject(jsonObject.getString("data"), User.class);
    }


    @Override
    public ResultVO globalList(ColumnDataPageVo columnDataPageVo) {
        IPage page = new Page();
        page.setSize(columnDataPageVo.getSize());
        page.setCurrent(columnDataPageVo.getCurrent());
        QueryWrapper<WebContent> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("website_id", WebsiteUtil.getWebsiteId());
        queryWrapper.eq("status", 1);
        if (StringUtils.isNotBlank(columnDataPageVo.getIntroduce())) {
            queryWrapper.and(wrapper -> wrapper.like("original_content", columnDataPageVo.getIntroduce()).or().like("content_title", columnDataPageVo.getIntroduce()));
        }
        //queryWrapper.and(wrapper -> wrapper.like("content", content));
        if (null != columnDataPageVo.getBeginDate()) {
            queryWrapper.ge("publish_time", columnDataPageVo.getBeginDate());
        }
        if (null != columnDataPageVo.getEndDate()) {
            queryWrapper.le("publish_time", columnDataPageVo.getEndDate());
        }
        if (columnDataPageVo.getId() != null) {
            queryWrapper.eq("id", columnDataPageVo.getId());
        }
        if (StringUtils.isNotBlank(columnDataPageVo.getCreatedBy())) {
            queryWrapper.like("created_by", columnDataPageVo.getCreatedBy());
        }
        queryWrapper.orderByDesc("publish_time");
        IPage result = contentMapper.selectPage(page, queryWrapper);
        List<WebContent> records = result.getRecords();
        LinkedList<WebContentVo> webContentVos = new LinkedList<>();
        for (WebContent record : records) {
            WebContentVo webContentVo = new WebContentVo();
            BeanUtils.copyProperties(record, webContentVo);
            Integer click = clickRateMapper.getClick(webContentVo.getId());
            if (click == null) {
                click = NumberConstant.NUMBER_0;
            }
            webContentVo.setClickRate(click);
            webContentVos.add(webContentVo);
        }
        result.setRecords(webContentVos);
        return ResultVO.data(result);
    }

    @Override
    public ResultVO replaceContent(ReplaceContentVo replaceContentVo) {
        String sourceTextIllegal = judgeReplaceAble(replaceContentVo.getSourceText());
        if (sourceTextIllegal != null) {
            return ResultVO.fail("包含不能被替换词" + sourceTextIllegal);
        }
        String targetTextIllegal = judgeReplaceAble(replaceContentVo.getTargetText());
        if (targetTextIllegal != null) {
            return ResultVO.fail("包含不能被替换词" + targetTextIllegal);
        }
        List<Integer> contentIds = replaceContentVo.getContentIds();
        if (contentIds.size() < 1) {
            return ResultVO.fail(ResultCode.PARAM_INVALID);
        }
        contentMapper.repalceContent(replaceContentVo.getSourceText(), replaceContentVo.getTargetText(), replaceContentVo.getContentIds());
        return ResultVO.success(ResultCode.SUCCESS);
    }

    private String judgeReplaceAble(String text) {
        if (StringUtils.isNotBlank(text)) {
            boolean contains = MathcingConfig.completeMatchingSet.contains(text);
            if (contains) {
                return text;
            }
            for (String fuzzyWord : MathcingConfig.fuzzyMatchingSet) {
                if (text.contains(fuzzyWord)) {
                    return fuzzyWord;
                }
            }
        }
        return null;
    }

}
